------------------------------------------------------------------------------
-- Serialization library for computercraft by Hea3veN
-- Version 0.1
------------------------------------------------------------------------------
-- Example:
--
--     -- The following script counts the amount of times it has been run
--	   loadfile("serialize.lua")()
--
--	   PROG_DATA_NAME = "myProgData"
--
--	   myData = unserialize(PROG_DATA_NAME)
--	   if myData == nil then
--	       myData = {}
--	       myData.runCount = 1
--	   end
--
--	   print("This program has been run "..tostring(myData.runCount).." time(s)")
--
--	   myData.runCount = myData.runCount + 1
--	   serialize(PROG_DATA_NAME)
--			
-- Interface:
--
--     serialize(data, name)
--        Save the table *data* to a file with *name* in the directory /var.
--
--     unserialize(name)
--        Read and load a saved table from a file in the directory /var with
--        *name* and return it.
--

function serialize(data, name)
	if not fs.exists('/data') then
		fs.makeDir('/data')
	end
	local f = fs.open('/data/'..name, 'w')
	f.write(textutils.serialize(data))
	f.close()
end

function unserialize(name)
	if fs.exists('/data/'..name) then
		local f = fs.open('/data/'..name, 'r')
		data = textutils.unserialize(f.readAll())
		f.close()
		return data
	else
		return nil
	end
end
